import {
    ProFormInstanceType,
    ProFormText,
    QueryFilter
} from '@ant-design/pro-components';
import Editor from '@monaco-editor/react';
import {request, useRequest} from '@umijs/max';
import {Button, Col, Form, FormInstance, Input, message, Modal, Row, Switch, Table} from 'antd';
import {useRef, useState} from 'react';

type Query = {name: string; pageNum?: number; pageSize: number;}

const Model = () => {
    const ref = useRef<FormInstance>(null)
    const filterForm = useRef<ProFormInstanceType<any>>(null)
    const [open, setOpen] = useState(false)
    const [record, setRecord] = useState<Record<string, any>>({})
    const {run: createModel} = useRequest( (content: string, name: string, description: string) => {
            return request('/api/model', {
                method: 'POST',
                data: {
                    content,
                    name,
                    description,
                }
            });
        },
        {
            manual: true,
            onSuccess () {
                getModel(filterForm.current?.getFieldsFormatValue?.() ?? {})
            },
            onError: (e) => {
                message.error(e.message);
            },
        },
    );

    const {run: getModel, data: dataSource, loading: listLoading} = useRequest(
        (params?: Query) => {
            return request('/api/model', {
                method: 'GET',
                params,
            });
        },
        {
            manual: true,
            onError: (e) => {
                message.error(e.message);
            },
        },
    );

    const {run: updateModel} = useRequest(
        (record) => {
            return request(`/api/model/${record.id}`, {
                method: 'patch',
                data: {
                    ...record
                },
            });
        },
        {
            manual: true,
            onSuccess () {
                getModel(filterForm.current?.getFieldsFormatValue?.() ?? {})
            },
            onError: (e) => {
                message.error(e.message);
            },
        },
    );

    const {run: deleteModel} = useRequest(
        (id: string) => {
            return request(`/api/model/${id}`, {
                method: 'DELETE',
            });
        }, {
        manual: true,
        onSuccess () {
            message.success('删除成功')
            getModel(filterForm.current?.getFieldsFormatValue?.() ?? {})
        },
        onError: (e) => {
            message.error(e.message);
        },
    })

    const columns = [
        {
            title: '模型名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
        },
        {
            title: '默认',
            dataIndex: 'default',
            key: 'default',
            render: (text: boolean, record: any) => <Switch value={Boolean(text)} onChange={v => updateModel({...record, default: Boolean(v)})} />,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            render: (text: string, record: any) => (
                <>
                    <Button type='text' onClick={() => {
                        setOpen(true)
                        setRecord(record)
                    }}>编辑</Button>

                    <Button type='text' onClick={() => {
                        deleteModel(record.id)
                    }}>删除</Button>
                </>
            )
        }
    ]

    // useEffect(() => {
    //     getModel()
    // }, [])

    return (
        <>
            <QueryFilter
                formRef={filterForm}
                defaultCollapsed
                split
                initialValues={{}}
                onFinish={(formData: Query) => {
                    getModel({...formData})
                }}
                onInit={(formData: Query) => {
                    getModel({...formData})
                }}
            >
                <ProFormText name="name" label="模型名称" />
            </QueryFilter>
            <Row justify={'end'}>
                <Col>
                    <Button type='primary' onClick={() => {
                        setOpen(true)
                    }}>新建模型</Button>
                </Col>
            </Row>
            <Table
                loading={listLoading}
                dataSource={dataSource}
                columns={columns}
                tableLayout="fixed"
            />

            <Modal
                title={record.id ? '编辑模型' : '新建模型'}
                open={open}
                width={1000}
                onCancel={() => {
                    setOpen(false)
                    setRecord({})
                }}
                onClose={() => {
                    // ref.current?.resetFields()
                }}
                onOk={async () => {
                    try {
                        const values = await ref.current?.validateFields()
                        if (values.id) {
                            await updateModel(values)
                        } else {
                            await createModel(values.content, values.name, values.description)
                        }
                        setOpen(false)
                    } catch (error) {

                    }
                }}
                destroyOnClose
            >
                <Form ref={ref} labelCol={{span: 3}} initialValues={{...record}}>
                    <Form.Item name={'id'} hidden>
                        <Input />
                    </Form.Item>
                    <Form.Item name={'name'} label="模型名称" rules={[
                        {
                            required: true,
                            message: '请输入模型名称'
                        }
                    ]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name={'description'} label="描述" rules={[
                        {
                            required: true,
                            message: '请输入模型描述'
                        }
                    ]}>
                        <Input />
                    </Form.Item>
                    <Form.Item name={'default'} label="默认">
                        <Switch />
                    </Form.Item>
                    <Form.Item name={'content'} label="内容" rules={[
                        {
                            required: true,
                            message: '请输入模型内容'
                        }
                    ]}>
                        <Editor
                            height="400px"
                            defaultLanguage="typescript"
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default Model;
